import com.adobe.utils.StringUtil;

import flash.events.Event;
import flash.events.HTTPStatusEvent;
import flash.events.IOErrorEvent;
import flash.external.ExternalInterface;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.URLVariables;

import mx.controls.Alert;
import mx.utils.StringUtil;

private static const AUTH_SUCCESS_STATUS_CODE:Number = 200; 
private static const AUTH_BAD_CREDENTIALS_STATUS_CODE:Number = 403;
private static const LOGIN_URL:String =  'https://www.google.com/accounts/ClientLogin';
private static const SOURCE:String =  'youtunes-tau2010';
private static const target_authenticated_google_app_engine_uri:String = "http://youtunes-tau2010.appspot.com/";
private var connected:Boolean = false;
private var authToken:String;

public function authenticate(login: String, password: String): void 
{
	var authRequest:URLRequest = new URLRequest();
	authRequest.url = LOGIN_URL;
	authRequest.method = "POST";
	var variables: URLVariables = new URLVariables();
	variables.service = "ah";
	variables.source = SOURCE;
	variables.Email = login;
	variables.Passwd = password;
	authRequest.data = variables;
	
	var authConnection:URLLoader = new URLLoader();
	authConnection.addEventListener(Event.COMPLETE,handleAuthResultEvent);
	authConnection.addEventListener(IOErrorEvent.IO_ERROR, handleAuthFaultEvent);
	authConnection.addEventListener(HTTPStatusEvent.HTTP_STATUS, handleAuthStatusEvent);
	
	authConnection.load(authRequest);	
	
}

private function handleAuthResultEvent(event: Event): void 
{
	var result:String = String(event.target.data);
	//manually parsing out the Auth name/value pair
	var tokens:Array = result.split(/[\n=]/);
	var urlloader:URLLoader = event.target as URLLoader;
	urlloader.removeEventListener(Event.COMPLETE, handleAuthResultEvent);
	urlloader.removeEventListener(IOErrorEvent.IO_ERROR, handleAuthFaultEvent);
	for(var i:int = 0; i < tokens.length; i++) 
	{
		if((tokens[i] == "Auth") && (i+1 != tokens.length)) 
		{
			authToken = tokens[i+1];
			connected = true;
			break;
		}
	}
	if(connected){
		handleToken();
	} else {
		Alert.show("Failed to login, please try again.");
		trace("Failed to connect");
	}
}

private function handleAuthFaultEvent(event: IOErrorEvent): void 
{
	connected = false;
	var urlloader:URLLoader = event.target as URLLoader;
	urlloader.removeEventListener(Event.COMPLETE, handleAuthResultEvent);
	urlloader.removeEventListener(IOErrorEvent.IO_ERROR, handleAuthFaultEvent);
	trace(event.toString());
	
	var errorMessage:String = new String();
	var googleRespOrig:String = String(urlloader.data);
	if (googleRespOrig.length != 0)
	{
		
		var googleResp:String = googleRespOrig;
		var erridx:int = googleRespOrig.indexOf("Error=");
		if ( erridx > -1 )
		{
			googleResp = googleResp.substring(erridx + 6);
		}
		if ( googleResp == "CaptchaRequired" )
		{
			erridx = googleRespOrig.indexOf("Url=");
			if ( erridx > -1 )
			{						
				googleResp = "Please authenticate in your browser against the captcha. This is for security reasons.";
			}
			
		}
		if (googleResp.indexOf("BadAuthentication") > -1)
		{
			googleResp = "invalid user/password"
		}
		errorMessage = "Authentication failed: " + googleResp;
	}
	else
	{
//		errorMessage = "Unable to connect to Google Service";
		errorMessage = "Please check your internet connectivity and try again.";
	}
	
	Alert.show(errorMessage);	
}

private function handleAuthStatusEvent(event: HTTPStatusEvent) : void 
{
	var urlStream:URLLoader = event.target as URLLoader;
	urlStream.removeEventListener(HTTPStatusEvent.HTTP_STATUS, handleAuthStatusEvent);
	
	trace(event.status);
	if(event.status == AUTH_SUCCESS_STATUS_CODE)
	{ 
		return;
	} 
	else if(event.status == AUTH_BAD_CREDENTIALS_STATUS_CODE)
	{
//		Alert.show("Failed to login, invalid user/password");
		trace("Faild to login, invalid user/password");
	}
}

private function handleToken():void
{
	var variables: URLVariables = new URLVariables();
	variables.decode("continue="+target_authenticated_google_app_engine_uri);
	variables.auth = authToken;
	var full_serv_uri:String = target_authenticated_google_app_engine_uri+"_ah/login?%s&"+variables.toString();
	
	var urlLoader:URLLoader = new URLLoader();
	urlLoader.addEventListener(Event.COMPLETE,handleFinishAuthResultEvent);
	urlLoader.addEventListener(IOErrorEvent.IO_ERROR, handleAuthFaultEvent);
	urlLoader.addEventListener(HTTPStatusEvent.HTTP_STATUS, handleAuthStatusEvent);
	
	urlLoader.load(new URLRequest(full_serv_uri));
	
}

private function handleFinishAuthResultEvent(event: Event):void 
{
	dispatchEvent(new Event(YouTunes.closeLoginPopup,true));
}